package cn.org.custom.client;

import cn.org.custom.client.handler.InboundHandlerAdapter;
import cn.org.custom.protocol.ProcotolFrameDecoder;
import cn.org.custom.utils.CloseTool;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import static cn.org.custom.client.constants.Constants.*;


@Slf4j
public class ChatClient {
    public static void main(String[] args) {
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();

                    pipeline.addLast(new ProcotolFrameDecoder());
//                    pipeline.addLast(LOGGING_HANDLER);
                    /**
                     * 编解码器
                     */
                    pipeline.addLast(MESSAGE_CODEC);

                    /**
                     * 心跳
                     */
                    pipeline.addLast(IDLE_STATE_HANDLER);
                    pipeline.addLast(HEART_BEAT_HANDLER);

                    /**
                     * 自定义业务处理器
                     */
                    pipeline.addLast(PONG_MESSAGE_HANDLER);
                    pipeline.addLast(CHAT_RESPONSE_MESSAGE_HANDLER);
                    pipeline.addLast(GROUP_CHAT_RESPONSE_HANDLER);
                    pipeline.addLast(GROUP_CREATE_RESPONSE_HANDLER);
                    pipeline.addLast(GROUP_JOIN_RESPONSE_HANDLER);
                    pipeline.addLast(GROUP_MEMBERS_RESPONSE_HANDLER);
                    pipeline.addLast(GROUP_QUIT_RESPONSE_MESSAGE_HANDLER);
                    pipeline.addLast(LOGIN_RESPONSE_MESSAGE_HANDLER);

                    pipeline.addLast("client handler", new InboundHandlerAdapter());
                }
            });
            Channel channel = bootstrap.connect("localhost", 8080).sync().channel();
            log.info("----------启动成功----------");
            channel.closeFuture().sync();
        } catch (Exception e) {
            log.error("client error", e);
        } finally {
            CloseTool.closeEventLoopGroup(group);
        }
    }
}
